from xml.etree import ElementTree
from swedish_geoposition_converter import *

class Coordinate:
	""" Normalises a Facility Coordinate to vanilla SWEREF99 (~WGS84) from SWEREF99 2015 """
	def __init__(self, element):
		self.lat = None
		self.lon = None

		for projection in [ 'LU', 'RT90' ]:
			grid_x = element.find(projection + '_X').text
			grid_y = element.find(projection + '_Y').text

			if grid_x == None or grid_y == None or grid_x == "0" or grid_y == "0":
				continue	# empty value for this coordinate type

			grid_x = str(grid_x).replace(',', '.')
			grid_y = str(grid_y).replace(',', '.')
			
			grid_x, grid_y = list(map(float, [ grid_x, grid_y ]))

			# convert non-WGS84 to vanilla SWEREF99 (which is close enough to WGS84)
			if projection == 'LU':
				# LU is not used,anymore, nowadays this field has SWEREF99 20 15 (dd mm)
				converter = SwedishGeoPositionConverter('sweref_99_2015')
				self.lat, self.lon = converter.gridToGeodetic(grid_x, grid_y)
			elif projection == 'RT90':
				converter = SwedishGeoPositionConverter('rt90_2.5_gon_v')
				self.lat, self.lon = converter.gridToGeodetic(grid_x, grid_y)
			break

		if self.lat == None or self.lon == None:
			self.lat = element.find('WGS84_LAT').text
			self.lon = element.find('WGS84_LONG').text

		if self.lat == None or self.lon == None:
			raise ValueError("Bad or no coordinates")

	def __str__(self, projection=None):
		if self.lat == None or self.lon == None:
			return None

		if projection != None:
			converter = SwedishGeoPositionConverter(projection)
			return "{0},{1}".format(converter.geodeticToGrid(self.lat, self.lon))
			
		return "{0},{1}".format(self.lat, self.lon)
class Facility:
	""" The Facility object is initialised with an XML Element """

	ID = None
	Coordinate = None

	def __init__(self, element):
		self.__class__.ID = int(element.attrib['ID'])

		for tag in [ 'Name', 'Buildingtype' ]:
			setattr(self.__class__, tag, str(element.find(tag).text))

		self.__class__.Coordinate = Coordinate(element.find('Coordinate'))

		self.element = element
	
	def __str__(self, xml=True):
		return ElementTree.tostring(self.element, encoding='utf-8').decode('utf-8')
	
	def cols(self):
		return '{0}\t{1}\t{2}\t{3}\t{4}'.format(self.ID, self.Coordinate.lat, self.Coordinate.lon, self.Name, self.Buildingtype)
